package com.example.datn.activities;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.example.datn.R;
import com.example.datn.manager.AlbumManager;
import com.example.datn.manager.ResourceManager;
import com.example.datn.manager.SongManager;
import com.example.datn.objects.SongObject;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

public class PlayMediaActivity extends Activity implements OnBufferingUpdateListener, OnCompletionListener, OnTouchListener, OnClickListener{

	private TextView tv_songName, tv_albumName, tv_luotNghe, tv_luotThich, tv_timer;
	private SeekBar sb_songTimeProgress;
	private ImageButton btn_play_pause, btn_replay, btn_previousSong, btn_nextSong, btn_likeSong, btn_shareSong;
    private final Handler handler = new Handler();
    private MediaPlayer mediaPlayer;
    private  SongObject song;
    boolean isLoadingSong = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.play_media_screen);
		initViews();		
		refresh();				
	}

	private void initViews() {
		tv_songName  = (TextView)findViewById(R.id.songName_playMusic);
		tv_albumName = (TextView)findViewById(R.id.albumName_playMusic);
		tv_luotNghe  = (TextView)findViewById(R.id.luotNghe_playMsic);
		tv_luotThich = (TextView)findViewById(R.id.luotThich_playMsic);
		tv_timer 	 = (TextView)findViewById(R.id.tv_timer_playMedia);
		sb_songTimeProgress = (SeekBar)findViewById(R.id.seekbar_song_timeProgress);		
		
		btn_play_pause = (ImageButton)findViewById(R.id.ibtn_play_pause_playMedia);		
		btn_play_pause.setOnClickListener(this);
		btn_likeSong =(ImageButton)findViewById(R.id.ibtn_like_playMedia);
		btn_likeSong.setOnClickListener(this);
		btn_nextSong = (ImageButton)findViewById(R.id.ibtn_next_displayMedia);
		btn_nextSong.setOnClickListener(this);
		btn_previousSong = (ImageButton)findViewById(R.id.ibtn_previous_displayMedia);
		btn_previousSong.setOnClickListener(this);
		btn_replay = (ImageButton)findViewById(R.id.ibtn_replay_displayMedia);
		btn_replay.setOnClickListener(this);
		btn_shareSong = (ImageButton)findViewById(R.id.ibtn_share_playMedia);
		btn_shareSong.setOnClickListener(this);
	}
	
	@Override
	public void onBackPressed() {		
		super.onBackPressed();		
		Intent i = new Intent(this, SongsViewActivity.class);
		this.startActivity(i);
		finish();
	}

	//chay seekbar
    private void primarySeekBarProgressUpdater() {
    	try{
    		int time = mediaPlayer.getCurrentPosition()/1000;
    		//hien thi dong ho thoi gian chay nhac
    		tv_timer.setText(SongManager.convertTime(time) + " | " + 
    					SongManager.convertTime(mediaPlayer.getDuration()/1000));
    		sb_songTimeProgress.setProgress(time);
        	
        	if(mediaPlayer.isPlaying()){
        		Runnable notification = new Runnable() {				
    				@Override
    				public void run() {
    					primarySeekBarProgressUpdater();
    				}
    			};
    			handler.postDelayed(notification,1000);
        	}
    	}catch(Exception e){Log.d("---------------", e.toString());}
    }

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public void onCompletion(MediaPlayer mp) {
		nextSong();		
	}

	//bat su kien buffer music
	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		sb_songTimeProgress.setSecondaryProgress(percent*mediaPlayer.getDuration()/100);
	}

	@Override
	public void onClick(View v) {
		if(!isLoadingSong){
			switch (v.getId()) {
			case R.id.ibtn_play_pause_playMedia:
				if(mediaPlayer.isPlaying()){
					mediaPlayer.pause();
					btn_play_pause.setImageResource(R.drawable.ic_action_play1);
				}
				else{
					mediaPlayer.start();
					btn_play_pause.setImageResource(R.drawable.ic_action_pause1);
				}
				primarySeekBarProgressUpdater();
				break;

			case R.id.ibtn_next_displayMedia:
				nextSong();
				break;
			case R.id.ibtn_previous_displayMedia:
				previousSong();
				break;
			}
		}
	}	
	
	private void nextSong() {
		SongObject song = SongManager.getNextSong();
		SongManager.getInstance().setCurrentSong(song);		
		
		if(mediaPlayer.isPlaying())
			mediaPlayer.pause();		
		try {
			if(song.linkAudio == null || song.linkAudio == "")
				new getLinkAudioTask().execute(song);
			else
				playMedia(song.linkAudio);
		} catch (Exception e) {
			Log.d("error load media", "can't next song - error - " + e.toString());
		} 
	}
	
	private void previousSong(){
		SongObject song = SongManager.getPreviousSong();
		SongManager.getInstance().setCurrentSong(song);
		
		if(mediaPlayer.isPlaying())
			mediaPlayer.pause();		
		try {
			if(song.linkAudio == null || song.linkAudio == "")
				new getLinkAudioTask().execute(song);
			else
				playMedia(song.linkAudio);
		} catch (Exception e) {
			Log.d("error load media", "can't previous song - error - " + e.toString());
		} 
	}
	
	private void refresh(){
		//refresh lai cac thong tin bai hat
		SongObject song = SongManager.getInstance().getCurrentSong();
		tv_songName.setText(song.songName);
		tv_albumName.setText(song.albumName);
		tv_luotThich.setText(""+song.luotThich);
		tv_luotNghe.setText(""+song.luotNghe);
		
		//refresh lai button next va prev
		if(song.songNo == 1)
			btn_previousSong.setVisibility(View.INVISIBLE);
		else if(song.songNo == SongManager.getInstance().getListSong().size())
			btn_nextSong.setVisibility(View.INVISIBLE);
		else{
			btn_previousSong.setVisibility(View.VISIBLE);
			btn_nextSong.setVisibility(View.VISIBLE);
		}
		
		//refresh lai button pause/play
		if(mediaPlayer == null)
			mediaPlayer = SongManager.getInstance().getCurrentMediaPlayer();
		if(mediaPlayer.isPlaying())
			btn_play_pause.setImageResource(R.drawable.ic_action_pause1);
		else
			btn_play_pause.setImageResource(R.drawable.ic_action_play1);
				
		sb_songTimeProgress.setMax(mediaPlayer.getDuration()/1000);
		primarySeekBarProgressUpdater();		
	}
	
	//asynctask de load link audio
	private class getLinkAudioTask extends AsyncTask<SongObject, Void, Void>{
	    	SongObject song;
	    	String link = "";
	    	
	    	@Override
			protected void onPreExecute() {	
	    		isLoadingSong = true;
	    		tv_songName.setText("loading...");
	    		tv_albumName.setText("");
	    		tv_luotThich.setText("");
	    		tv_luotNghe.setText("");

				super.onPreExecute();
			}
	    	
			@Override
			protected Void doInBackground(SongObject... params) {			
				try {			
					Document doc;						
					song = params[0];
					doc = Jsoup.connect(song.urlSong).get();				
					String a = doc.toString(),b;								
					Pattern pattern = Pattern.compile("xmlURL=([^&]*)");
					Matcher matcher = pattern.matcher(a);
					if (matcher.find()){
					    b = matcher.group(1);			    			   
					    doc = Jsoup.connect(b).get();				
						pattern = Pattern.compile("</source>(.+?)=");
						matcher = pattern.matcher(doc.toString());
						if (matcher.find()){
							link = matcher.group(1);
						}
					}				
				} catch (IOException e) {
					e.printStackTrace();
				}		
				
				song.linkAudio = link;
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {			
				super.onPostExecute(result);			
				if(song.linkAudio != "")
					playMedia(link);
					//new LoadMediaTask().execute(song.linkAudio);
			}
	    }
	
	//chay media tu url
	private void playMedia(String url){
		isLoadingSong = true;
		tv_songName.setText("loading...");
		tv_albumName.setText("");
		tv_luotThich.setText("");
		tv_luotNghe.setText("");
				
		if(mediaPlayer == null){
			mediaPlayer = new MediaPlayer();			
		}	
		else if(mediaPlayer.isPlaying()){
			mediaPlayer.stop();			
		}
		mediaPlayer.reset();
        //mediaPlayer = new MediaPlayer();	        
        try {
			mediaPlayer.setDataSource(url);
			mediaPlayer.prepare();
		} catch (Exception e) {
			e.printStackTrace();
		} 			
        
        mediaPlayer.start();					
		mediaPlayer.setOnCompletionListener(PlayMediaActivity.this);
		SongManager.getInstance().setCurrentMediaPlayer(mediaPlayer);	
		refresh();
		isLoadingSong = false;
		
	}		
	
}
